Broadcasting using websocket

  • STEPS 1 : Websocket integration

    Step 1:install WebSocket

    
                  composer require beyondcode/laravel-websockets
    

    Step 2:Apply command once install WebSocket successfully

    
    php artisan vendor:publish --provider="BeyondCode\LaravelWebSockets\WebSocketsServiceProvider" --tag="migrations"
    

    Step 3:Run migration

    
    php artisan migrate
    

    Step 4: publish WebSocket configuation

    
    php artisan vendor:publish --provider="BeyondCode\LaravelWebSockets\WebSocketsServiceProvider" --tag="config"
    

    in config/websockets.php

    
    'dashboard' => [
            'port' => env('LARAVEL_WEBSOCKETS_PORT', 6001),
        ],
    
        /*
         * This package comes with multi tenancy out of the box. Here you can
         * configure the different apps that can use the webSockets server.
         *
         * Optionally you specify capacity so you can limit the maximum
         * concurrent connections for a specific app.
         *
         * Optionally you can disable client events so clients cannot send
         * messages to each other via the webSockets.
         */
        'apps' => [
            [
                'id' => env('PUSHER_APP_ID'),
                'name' => env('APP_NAME'),
                'key' => env('PUSHER_APP_KEY'),
                'secret' => env('PUSHER_APP_SECRET'),
                'path' => env('PUSHER_APP_PATH'),
                'capacity' => null,
                'enable_client_messages' => false,
                'enable_statistics' => true,
            ],
        ],
    

    Step 6: install pusher

    To make use WebSockets package of laravel with combination of pusher you can need to install pusher first

    
    composer require pusher/pusher-php-server "~3.0"
    

    Step 7: setup broadcast driver .env file

    You need to use pusher as broadcasting driver into laravel so below line setup into .env file BROADCAST_DRIVER=pusher

    don't forget to uncomment below line on app.php that is not defined into documentation App\Providers\BroadcastServiceProvider::class

    in .env

    
    BROADCAST_DRIVER=pusher
    
    
    PUSHER_APP_ID=123456
    PUSHER_APP_KEY=good
    PUSHER_APP_SECRET=morning
    #PUSHER_HOST=
    #PUSHER_PORT=443
    #PUSHER_SCHEME=https
    PUSHER_APP_CLUSTER=mt1
    
    Assign something to PUSHER_APP_ID, PUSHER_APP_KEY, and PUSHER_APP_SECRET

    in config/broadcasting.php

    
    'pusher' => [
                'driver' => 'pusher',
                'key' => env('PUSHER_APP_KEY'),
                'secret' => env('PUSHER_APP_SECRET'),
                'app_id' => env('PUSHER_APP_ID'),
                'options' => [
                    'cluster' => env('PUSHER_APP_CLUSTER'),
                    'host' => '127.0.0.1',
                    'port' => 6001,
                    'scheme' => 'http',
                    'encrypted' => true,
                    //'useTLS' => env('PUSHER_SCHEME', 'https') === 'https',
                ],
                'client_options' => [
                    // Guzzle client options: https://docs.guzzlephp.org/en/stable/request-options.html
                ],
            ],
    
        
  • STEPS 2 : laravel-echo integration

    1. install laravel echo

    
                    npm install --save-dev laravel-echo pusher-js
                    

    Now we have to configure laravel-echo in resources/js/bootstrap.js .

    2. resources/js/bootstrap.js

    
                    import axios from 'axios';
    window.axios = axios;
    
    window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
    
    /**
     * Echo exposes an expressive API for subscribing to channels and listening
     * for events that are broadcast by Laravel. Echo and event broadcasting
     * allows your team to easily build robust real-time web applications.
     */
    
    import Echo from 'laravel-echo';
    
    import Pusher from 'pusher-js';
    window.Pusher = Pusher;
    
    window.Echo = new Echo({
        broadcaster: 'pusher',
        key: import.meta.env.VITE_PUSHER_APP_KEY,
        cluster: import.meta.env.VITE_PUSHER_APP_CLUSTER ?? 'mt1',
        wsHost: window.location.hostname,
        wsPort: 6001,
       // wssPort: import.meta.env.VITE_PUSHER_PORT ?? 443,
       // forceTLS: (import.meta.env.VITE_PUSHER_SCHEME ?? 'https') === 'https',
        forceTLS: false,
        enabledTransports: ['ws', 'wss'],
        disableStats: true,
    });
    
        window.Echo.channel(`channel-name`)
        .subscribed(() => {
            console.log("Echo connected to PieSocket channel!");
        })
        .listen('MessageEvent', (data) => {
            alert("New Resume from "+data.name);
            console.log("New Resume Received", data);
            document.getElementById('notification_panel').innerHTML+='<tr><td>'+data.position+'</td><td>'+data.qualification+'</td><td>'+data.experience+'</td><td>'+data.name+'</td><td>'+data.email+'</td><td>'+data.mobile+'</td></tr>';
        });
    
    

    add bootstrap.js in view page

    
            <h2>Notification Testing</h2>
    
            <table id="notification_panel" class="table table-bordered">
                    <tr>
                        <th>Position</th>
                        <th>Qualification</th>
                        <th>Experience</th>
                        <th>Name</th>
                        <th>Email</th>
                        <th>Mobile</th>
           </table>
    
            @vite('resources/js/app.js', 'vendor/courier/build')
    
    
    
    
  • STEPS 3 : Broadcasting Channel Integration

    add new events in app\Events\

    app\Events\MessageEvent.php

    
                        namespace App\Events;
     
     use Illuminate\Broadcasting\Channel;
     use Illuminate\Broadcasting\InteractsWithSockets;
     use Illuminate\Broadcasting\PresenceChannel;
     use Illuminate\Broadcasting\PrivateChannel;
     use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
     use Illuminate\Foundation\Events\Dispatchable;
     use Illuminate\Queue\SerializesModels;
      
     class MessageEvent  implements ShouldBroadcast
     {
         use Dispatchable, InteractsWithSockets, SerializesModels;
         
         private $order;
      
         /**
          * Create a new event instance.
          *
          * @return  void
          */
         public function __construct($data=[])
         {
             $this->order = $data;
         }
      
         public function broadcastWith()
         {
             return $this->order;
         }
      
         /**
          * Get the channels the event should broadcast on.
          *
          * @return  \Illuminate\Broadcasting\Channel|array
          */
         public function broadcastOn()
         {
             return new Channel('channel-name');
         }
     }
    
    

    Trigger the channel

    in the controller file

    
    use App\Events\MessageEvent;
    
    ...... 
    
    ...... 
    
    
    broadcast(new MessageEvent(['name'=>$r->name, 'email'=>$r->email, 'mobile'=>$r->mobile, 'position'=>$r->position, 'qualification'=>$r->qualification, 'experience'=>$r->experience]));
    
    
  • STEPS 4 :Testing

    1. Open 2 terminal windows

    2. in first window , run

    
                        npm run dev 
                        

    3. in second window, run

    
                        php artisan websocket:serve
                        

    4. call the route of function defined in the controller for broadcasting